package com.verlet.springbootdemo.config;

import com.verlet.springbootdemo.filter.IgnoreAuthInterceptor;
import com.verlet.springbootdemo.filter.MyFilter;
import com.verlet.springbootdemo.handler.CurrentUserMethodArgumentResolver;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jakarta.servlet.Filter;
import java.util.List;

/**
 * web 配置
 *
 * @author verlet
 * @date 2020/4/9
 */
@Configuration
@ConditionalOnProperty(prefix = "servlet", name = "interceptor")
public class WebConfig implements WebMvcConfigurer {

    /**
     * 配置Filter 可以配置Filter顺序
     */
    @Bean
    @ConditionalOnProperty(prefix = "servlet", name = "filter")
    public FilterRegistrationBean<Filter> filterRegistrationBean() {
        FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new MyFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setName("filterBean");
        // filter 可以顺序配置
        filterRegistrationBean.setOrder(1);
        return filterRegistrationBean;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new IgnoreAuthInterceptor())
                // 需要拦截的路径
                .addPathPatterns("/**")
                // 不拦截路径
                .excludePathPatterns("/api/path/login", "/", "/index.html", "/favicon.ico", "/temperature-stream", "/error");
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new CurrentUserMethodArgumentResolver());
    }
}
